package tralala.server.dao;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

import tralala.server.data.Reproduccion;
import tralala.server.data.dto.ReproduccionDTO;

public class ReproduccionJDO {

	private PersistenceManager pm = null;
	private UsuarioJDO us;
	private CancionJDO canc;
	
	public ReproduccionJDO(){
		pm = DAO.getInstance().connect();
		us = new UsuarioJDO();
		canc = new CancionJDO();
	}
	
	public void guardar(Reproduccion repr){
		Transaction tx = pm.currentTransaction();
		try{
			tx.begin();
			pm.makePersistent(repr);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
		} finally {
		    if (tx.isActive()) {
		        tx.rollback();
		    }
		}
	}
	
	
	public void borrar(ReproduccionDTO repr){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		Reproduccion r = this.getReproduccionPorID(repr.getId());
		pm.deletePersistent(r);
		tx.commit();
	}
	
	public Reproduccion getReproduccionPorID(String id){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		Query query = pm.newQuery("SELECT FROM " + Reproduccion.class.getName() + " WHERE id =='" + id +  "'");
		query.setUnique(true);
		Reproduccion r = (Reproduccion) query.execute();
		tx.commit();
		return r;
	}
	
	
	public List<Reproduccion> getReproducciones(){
		Transaction tx = pm.currentTransaction();
		tx.begin();
		Query query = pm.newQuery("SELECT FROM " + Reproduccion.class.getName());
		@SuppressWarnings("unchecked")
		List<Reproduccion> listaReproducciones = (List<Reproduccion>) query.execute();
		tx.commit();
		return listaReproducciones;
	}

	public void nuevaReproduccion(ReproduccionDTO rep){
		Transaction tx = pm.currentTransaction();
		Reproduccion reproduccion = new Reproduccion(rep.getId(), rep.getFecha(), canc.get(rep.getCancion()), us.get(rep.getUsuario()));
		try {
			tx.begin();
		    pm.makePersistent(reproduccion);
		    tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
			tx.rollback();
		} finally {
		    if (tx.isActive()) {
		        tx.rollback();
		    }
		}
  	}
	
}
